﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Aquaculture
{
    public class HealthAddCommandHandler : IRequestHandler<HealthAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Health> healthRepository;
        private readonly IMapper mapper;
        public HealthAddCommandHandler(IBaseRepository<T_Health> healthRepository, IMapper mapper)
        {
            this.healthRepository = healthRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(HealthAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            T_Health health = healthRepository.GetAll().FirstOrDefault(x => x.ID == request.ID);
            if (request.IsAddOrUpdateOrDel == 1)
            {

                result.Code = APIEnum.ok;
                result.Message = "添加成功";
                request.ID = 0;
                var model = mapper.Map<T_Health>(request);
                result.Data = await healthRepository.Add(model);
                return await Task.FromResult(result);
            }
            else if (request.IsAddOrUpdateOrDel == 2)
            {
                result.Code = APIEnum.ok;
                result.Message = "修改成功";
                
                var healthData = mapper.Map(request, health);
                result.Data = await healthRepository.Update(healthData);
                return await Task.FromResult(result);
            }
            else 
            {
                result.Code = APIEnum.ok;
                result.Message = "删除成功";
                var healthData = mapper.Map(request, health);
                healthData.IsDelete = true; 
                result.Data = await healthRepository.Update(healthData);
                return await Task.FromResult(result);
            }
            
        }
    }
}
